const app = new Vue({
	el: ".todoapp",
	created() {
		window.addEventListener("hashchange", this.setHash)
		this.setHash()

		// 自动执行函数里面获取到本地存储
		this.todoList = JSON.parse(window.localStorage.getItem("todoList") || "[]")
	},
	directives: {
		focus(el, bindings) {
			if(bindings.value) {
				el.focus()
			}
		}
	},
	data: {
		currentHash: "",
		inputVal: "",
		todoList: [],
		isSelectAll: false,
		currentIndex: ''
	},
	watch: {
		todoList: {
			handler(newValue) {
				// 设置全选状态
				this.isSelectAll = this.todoList.every((item)=> {
					return item.isChecked === true
				})

				this.setLocalStorage()
			},
			deep: true
		}
	},
	computed: {
		currentTodoList() {
			if(this.currentHash === "#/") {
				return this.todoList
			}else if(this.currentHash === "#/active") {
				return this.todoList.filter((item)=> {
					return item.isChecked === false;
				})
			}else if(this.currentHash === "#/completed") {
				return this.todoList.filter((item)=> {
					return item.isChecked === true;
				})
			}else {
				return this.todoList
			}
		},
		leftNum() {
			return this.todoList.reduce((total, item)=> {
				if(!item.isChecked) {
					total++
				}
				return total
			}, 0)
		}
	},
	methods: {
		setLocalStorage() {
			// 
			window.localStorage.setItem("todoList", JSON.stringify(this.todoList))
		},
		setHash() {
			this.currentHash = window.location.hash
		},
		// 清除所有
		clearAll() {
			this.todoList = this.todoList.filter((item)=> {
				return item.isChecked === false
			})
		},
		handlerBlur() {
			this.currentIndex = ""
		},
		joinEdit(index) {
			// 1.保存要处于编辑状态的索引值
			this.currentIndex = index;

			// this.$nextTick(()=> {
			// 	console.log(this.$refs.lists[index])
			// 	this.$refs.lists[index].focus();
			// 	// this.$refs.lists
			// })
		},
		changeAll() {
			this.todoList.forEach((item)=> {
				item.isChecked = this.isSelectAll
			})
		},
		addTodo() {
			if(!this.inputVal) return;
			this.todoList.push({
				isChecked: false,
				text: this.inputVal
			})

			this.inputVal = ""
		},
		delTodo(index) {
			this.todoList.splice(index, 1)
		}
	}
})